<template>
  <!-- 会员留存率 -->
  <div>
    <!-- 搜索框 -->
    <el-form ref="table_form" :model="table_form" class="table-search" :inline="true" label-width="100px">
      <el-form-item label="统计类型：" prop="type">
        <el-select clearable v-model="table_form.type" placeholder="请选择统计类型！" @change="handle_type">
          <el-option label="门店" value="store"></el-option>
          <el-option label="教练" value="coach"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="类型对象：" prop="select">
        <el-select multiple clearable v-model="table_form.select" placeholder="请选择类型对象！">
          <el-option
            v-for="item in type_data"
            :key="item.id"
            :label="table_form.type == 'store' ? item.storeAbbreviation : item.realName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="留存深度：" prop="retentionDepth">
        <el-input type="number" v-model="table_form.retentionDepth" placeholder="请输入留存深度！"></el-input>
      </el-form-item>
      <el-form-item label="统计日期：" prop="endTime">
        <el-date-picker 
          v-model="table_form.endTime" 
          type="date" 
          placeholder="请选择统计日期！" 
          value-format="yyyy-MM-dd" 
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handle_search">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="handle_reset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-tabs type="border-card" v-model="tab_name" @tab-click="change_tab">
      <el-tab-pane label="列表模式" name="1">
        <!-- 表格顶部的操作按钮 -->
        <div class="btn-box">
          <!-- 接口返回按钮 -->
          <div class="left"> </div>
          <!-- 表格列显示、隐藏 -->
          <div class="right">
            <el-popover
              placement="bottom-end"
              width="150"
              trigger="click">
              <el-checkbox v-model="checked_obj[0]">名称</el-checkbox>
              <el-checkbox v-model="checked_obj[1]">会员总数</el-checkbox>
              <el-checkbox v-model="checked_obj[2]">有效会员</el-checkbox>
              <el-checkbox v-model="checked_obj[3]">完课会员</el-checkbox>
              <el-checkbox v-model="checked_obj[4]">休眠会员</el-checkbox>
              <el-checkbox v-model="checked_obj[5]">沉默会员</el-checkbox>
              <el-checkbox v-model="checked_obj[6]">无订单会员</el-checkbox>
              <el-checkbox v-model="checked_obj[7]">3日沉默</el-checkbox>
              <el-checkbox v-model="checked_obj[8]">3日留存</el-checkbox>
              <el-checkbox v-model="checked_obj[9]">7日沉默</el-checkbox>
              <el-checkbox v-model="checked_obj[10]">7日留存</el-checkbox>
              <el-checkbox v-model="checked_obj[11]">30日沉默</el-checkbox>
              <el-checkbox v-model="checked_obj[12]">30日留存</el-checkbox>
              <el-button slot="reference" type="primary" icon="iconfont icon-faxianxuanze"></el-button>
            </el-popover>
            <!-- 导出excell -->
            <el-button type="primary" icon="iconfont icon-export" @click="handle_excell"></el-button>
          </div>
        </div>

        <!-- 表格 -->
        <el-table id="excell-table" :data="tableData" border header-cell-class-name="table-style">
          <el-table-column label="名称" align="center" min-width="160" v-if="checked_obj[0]">
            <template slot-scope="scope"> {{ set_table_name(scope.row) }} </template>
          </el-table-column>
          <el-table-column label="会员总数" align="center" v-if="checked_obj[1]">
            <template slot-scope="scope"> {{ scope.row.userListForType.length }} </template>
          </el-table-column>
          <el-table-column label="有效会员" align="center" v-if="checked_obj[2]">
            <template slot-scope="scope"> {{ scope.row.vaildVipUserList.length }} </template>
          </el-table-column>
          <el-table-column label="完课会员" align="center" v-if="checked_obj[3]">
            <template slot-scope="scope"> {{ scope.row.overCourseVipUserList.length }} </template>
          </el-table-column>
          <el-table-column label="休眠会员" align="center" v-if="checked_obj[4]">
            <template slot-scope="scope"> {{ scope.row.dormancyVipUserList.length }} </template>
          </el-table-column>
          <el-table-column label="沉默会员" align="center" v-if="checked_obj[5]">
            <template slot-scope="scope"> {{ scope.row.reticentVipUserList.length }} </template>
          </el-table-column>
          <el-table-column label="无订单会员" align="center" v-if="checked_obj[6]">
            <template slot-scope="scope"> {{ scope.row.noOrderVipUserList.length }} </template>
          </el-table-column>
          <el-table-column label="3日沉默" align="center" v-if="checked_obj[7]">
            <template slot-scope="scope"> {{ scope.row.reticentVipUserList3.length }} </template>
          </el-table-column>
          <el-table-column label="3日留存(%)" align="center" v-if="checked_obj[8]">
            <template slot-scope="scope"> {{ set_table_3day(scope.row) }} </template>
          </el-table-column>
          <el-table-column label="7日沉默" align="center" v-if="checked_obj[9]">
            <template slot-scope="scope"> {{ scope.row.reticentVipUserList7.length }} </template>
          </el-table-column>
          <el-table-column label="7日留存(%)" align="center" v-if="checked_obj[10]">
            <template slot-scope="scope"> {{ set_table_7day(scope.row) }} </template>
          </el-table-column>
          <el-table-column label="30日沉默" align="center" v-if="checked_obj[11]">
            <template slot-scope="scope"> {{ scope.row.reticentVipUserList30.length }} </template>
          </el-table-column>
          <el-table-column label="30日留存(%)" align="center" min-width="100" v-if="checked_obj[12]">
            <template slot-scope="scope"> {{ set_table_30day(scope.row) }} </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          background
          :current-page="table_form.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="10"
          layout="prev, pager, next, jumper, sizes, total"
          :total="total_page"
          @size-change="handle_size"
          @current-change="handle_page">
        </el-pagination>
      </el-tab-pane>
      <el-tab-pane label="数据可视化" name="2">
        <div class="echart-box" v-for="item in tableData" :key="item.obj.id" :id="'echart-' + item.obj.id"></div>
      </el-tab-pane>
    </el-tabs>

    
  </div>
</template>
<script>
import { selectByRule, selectCoachByRule } from '@/utils/apiStore.js'
import { retentionRateApi } from '@/utils/apiAnalysis.js'
export default {
  data() {
    return {
      tab_name: '1',
      table_form: {
        page:               1,      // 页数
        rows:               10,     // 每页显示条数
        type: '',
        select: '',
        retentionDepth: 1,
        endTime: this.G_time('', 2)
      },                        
      tableData:            [],     // 表格数据
      total_page:           0,      // 总条数
      checked_obj: {
        0: true,
        1: true,
        2: true,
        3: true,
        4: true,
        5: true,
        6: true,
        7: true,
        8: true,
        9: true,
        10: true,
        11: true,
        12: true
      },
      type_data: [],
      table_type: '',
      chart: ''
    }
  },
  mounted() {
    // 监听tab宽度变化，刷新表格图表
    window.addEventListener('resize', this.resize_echart)
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.resize_echart)
  },
  methods: {
    // tab切换事件 - 用于渲染图表
    change_tab() {
      if (this.tab_name == '2') {
        if (this.tableData.length) {
          let _width = document.querySelector('.el-tabs__content').offsetWidth
          this.tableData.forEach(item => {
            let echart_name = ''
            if (this.table_type == 'store') {
              echart_name = item.obj.storeName
            }
            if(this.table_type == "coach"){
              echart_name = item.obj.realName;
            }
            let tab_data = [ 
                    item.userListForType.length,
                    item.vaildVipUserList.length,
                    item.overCourseVipUserList.length,
                    item.reticentVipUserList.length,
                    item.noOrderVipUserList.length,
                    item.reticentVipUserList3.length,
                    item.keepVipUserList3.length,
                    item.reticentVipUserList7.length,
                    item.keepVipUserList7.length,
                    item.reticentVipUserList30.length,
                    item.keepVipUserList30.length 
                  ]
            document.querySelector(`#echart-${ item.obj.id }`).style.width = _width + 'px'
            this.init_table_echarts(`echart-${ item.obj.id }`, tab_data, echart_name)
          })
        }
      }
    },

    // 刷新图表
    resize_echart() {
      if (this.tab_name == '2') {
        if (this.tableData.length) {
          let _width = document.querySelector('.el-tabs__content').offsetWidth
          this.tableData.forEach(item => {
            let echart_name = ''
            if (this.table_type == 'store') {
              echart_name = item.obj.storeName
            }
            if(this.table_type == "coach"){
              echart_name = item.obj.realName;
            }
            let tab_data = [ 
                    item.userListForType.length,
                    item.vaildVipUserList.length,
                    item.overCourseVipUserList.length,
                    item.reticentVipUserList.length,
                    item.noOrderVipUserList.length,
                    item.reticentVipUserList3.length,
                    item.keepVipUserList3.length,
                    item.reticentVipUserList7.length,
                    item.keepVipUserList7.length,
                    item.reticentVipUserList30.length,
                    item.keepVipUserList30.length 
                  ]
            document.querySelector(`#echart-${ item.obj.id }`).style.width = _width + 'px'
            document.querySelector(`#echart-${ item.obj.id }`).style.height =  '500px'
            this.init_table_echarts(`echart-${ item.obj.id }`, tab_data, echart_name)
            this.chart.resize()
          })
        }
      }
    },

    // 参数组装
    set_params () {
      let params = JSON.parse(JSON.stringify(this.table_form))
      // 处理参数 时间
      if (params.endTime) {
        params.endTime = params.endTime + ' 23:59:59'
      } else {
        params.endTime = ''
      }

      // 分页重置
      params.page                = 1
      params.rows                = 10
      params.select              = params.select.join()

      return params
    },
    // 搜索
    handle_search() {
      // 非空校验
      if (!this.G_isempty(this.table_form.type)) {
        return this.$message.error({ message: '请选择统计类型！', offset: document.body.offsetHeight / 2 })
      }
      if (!this.G_isempty(this.table_form.select)) {
        return this.$message.error({ message: '请选择类型对象！', offset: document.body.offsetHeight / 2 })
      }
      this.table_type = this.table_form.type
      
      this.set_table(this.set_params())
    },

    // 重置resetFields
    handle_reset() {
      this.type_data                      = []
      this.$refs['table_form'].resetFields()
      this.table_form.page                = 1
      this.table_form.rows                = 10
      this.tableData                      = []
      this.total_page                     = 0
    },

    // 统计类型change事件
    handle_type(val) {
      this.type_data = []
      this.table_form.select = ''
      if (val == 'store') {
        selectByRule({ page: 1, rows: 9999 }).then(res => {
          if (res.errCode == 200) {
            this.type_data = res.data.elements
          }
        })
      } else if (val == 'coach') {
        selectCoachByRule({ page: 1, rows: 9999 }).then(res => {
          if (res.errCode == 200) {
            this.type_data = res.data.elements
          }
        })
      }
    },

    // 渲染表格方法
    set_table(params) {
      this.tableData        = []
      retentionRateApi(params).then(res => {
        if (res.errCode == 200) {
          this.tableData    = res.data
          this.total_page   = res.data.length
        }
      })
    },

    // 分页条数修改
    handle_size(rows) {
      this.table_form.rows = rows
      this.set_table(this.table_form)
    },

    // 页码数改变
    handle_page(page) {
      this.table_form.page = page
      this.set_table(this.table_form)
    },

    // 导出excell
    handle_excell() {
      this.$confirm('是否导出excell表格?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
          this.G_excell2()
      }).catch(action => {});
      
    },

    // 表格中名称处理函数
    set_table_name(data) {
      if (this.table_type == 'store') {
        return data.obj.storeName
      }
      if (this.table_type == 'coach') {
        return data.obj.realName
      }
    },

    // 表格中3日留存处理函数
    set_table_3day(data) {
      if ( data.vaildVipUserList.length == 0 ) {
          return 0
      } else {
          return (((( data.keepVipUserList3.length )/( data.vaildVipUserList.length ))*100).toFixed(2))
      }
    },

    // 表格中7日留存处理函数
    set_table_7day(data) {
      if ( data.vaildVipUserList.length == 0 ) {
          return 0
      } else {
          return (((( data.keepVipUserList7.length )/( data.vaildVipUserList.length ))*100).toFixed(2))
      }
    },

    // 表格中30日留存处理函数
    set_table_30day(data) {
      if ( data.vaildVipUserList.length == 0 ) {
          return 0
      } else {
          return (((( data.keepVipUserList30.length )/( data.vaildVipUserList.length ))*100).toFixed(2))
      }
    },

    // 表格图表化
    init_table_echarts (box_id, tab_data, echart_name) {
      let e_axis=["会员总数","有效会员数","完课会员","沉默会员","无订单会员","3日沉默","3日留存","7日沉默","7日留存","30日沉默","30日留存"];
      this.chart = this.$echarts.init(document.getElementById(box_id))
      let option = {
            title: {
                text: echart_name
            },
            tooltip: {},
            legend: {
                data:['总数']
            },
            xAxis: {
                data: e_axis
            },
            axisLabel: {
                show: true,
                interval:0,
                rotate:40,
            },
            yAxis: {},
            series: [{
                name: '数量',
                type: 'bar',
                data: tab_data
            }]
        }
      this.chart.setOption(option);
    }
  }
};
</script>

<style lang="scss" scoped>
</style>